// pages/map/search/index.js
import { search } from "../../../api/map";
import { deptList } from "../../../api/common";
import Notify from "../../../miniprogram_npm/@vant/weapp/notify/notify";
Component({
  properties: {
    defaultCity: String
  },

  data: {
    longitude: 113.324520,
    latitude: 23.099994,
    markers: [{
      id: 0,
      latitude: 23.099994,
      longitude: 113.324520,
    }],
    keywords: '',
    addressList: [],
    checkedAddress: {},
    cityList: [],
    city: ''
  },
  
  methods: {
    search () {
      const {keywords, city} = this.data
      if (!keywords) {
        this.setData({addressList: []})
        return
      }
      wx.showLoading({
        title: '查询中',
      })
      search({
        keywords: keywords,
        city: city,
      }).then(res => {
        console.log(res)
        const list = res.data.pois || []
        this.setData({
          addressList: list.filter(item => item.location).map(item => {
            const locations = item.location.split(',')
            return {
              ...item,
              longitude: locations[0],
              latitude: locations[1],
            }
          }),
        })
      }).finally(() => {
        wx.hideLoading();
      })
    },
    // 定位
    location(e) {
      const {markers} = this.data
      const {item} = e.currentTarget.dataset;
      markers[0].longitude = item.longitude;
      markers[0].latitude = item.latitude;
      this.setData({
        longitude: item.longitude,
        latitude: item.latitude,
        markers: markers,
        checkedAddress: item
      })
      console.log(item)
    },
    keywordInput(e) {
      this.setData({
        keywords: e.detail
      })
    },
    // 选择
    confirm() {
      if (this.data.checkedAddress && this.data.checkedAddress.name) {
        this.triggerEvent('confirm', {address: this.data.checkedAddress})
      } else {
        Notify({
          message: '请选择定位',
          type: 'danger'
        })
      }
    },
    cancel() {
      this.triggerEvent('cancel')
    },
    handleCityConfirm(e) {
      const {value} = e.detail
      this.setData({
        city: value
      })
    }
  },

  ready: function() {
    deptList().then(res => {
      this.setData({
        cityList: (res.data.result || []).map(item => item.deptName)
      })
    })
    this.setData({
      city: this.data.defaultCity
    })
  },

})